var htmlparser = require("htmlparser"),
	wikimapiaService = require('../services/wikimapiaService'),
	wikimapiaCategoryService = require('../services/wikimapiaCategoryService');

//argentinaBBox = '-75.014265,-55.919607,-54.359968,-21.853251';
var westLimit = -75.014265;
var northLimit = -55.919607;
var eastLimit = -54.359968;
var southLimit = -21.853251;
var lonDelta = 0.5;
var latDelta = 0.5;
var count = 50;
var category = false;

function fetchCategories() {
	fetchBox(westLimit, northLimit, westLimit + lonDelta, northLimit + latDelta);
}

function fetchBox(west, north, east, south) {
	
}


function setBbox(west, north, east, south) {
	return '' + west + ',' + north + ',' + east + ',' + south;
}

function fetchObjects(wikipamiaFolder, callback) {
	if (typeof(wikipamiaFolder) != 'undefined' && wikipamiaFolder != null && wikipamiaFolder.length > 0) {
		var count = 0;
		console.log("Extrayendo objetos");
		wikipamiaFolder.forEach(function (place) {
			count++;
			console.log("Call fetchObject");
			fetchObject(place.id);
			if (count >= wikipamiaFolder.length) {
				callback('ok');
			}
		});
	} else {
		callback('ok');
	}
}

function fetchObject(wikipamiaId) {
	wikimapiaService.wikimapiaGetObject(wikipamiaId, function(place) {
		console.log("Obteniendo objeto " + place.id);
		fetchTags(place.tags);
	});
}

function fetchTags(wikimapiaTags) {
	if (typeof(wikimapiaTags) != 'undefined' && wikimapiaTags != null) {
		console.log("Tags obtenidos " + JSON.stringify(wikimapiaTags));
		wikimapiaTags.forEach(function (tag) {
			saveTag(tag.title);			
		});
	}
}


function saveTag(tagId) {
	var tag = {};
	tag.id = tagId;
	wikimapiaService.execute('wikimapia.org', 80, '/object/category/?type=view&id=' + tagId + '&lng=0', 'get', function(response) {
		var dom = parseHtml(response);
		tag.title = dom[2].children[3].children[1].children[3].children[1].children[1].children[1].children[0].children[0].raw.replace(/ \([a-z]{2}\) /g,'');
		wikimapiaService.execute('wikimapia.org', 80, '/object/category/?type=view&id=' + tagId + '&lng=3', 'get', function(response) {
			dom = parseHtml(response);
			tag.title_es = dom[2].children[3].children[1].children[3].children[1].children[1].children[1].children[0].children[0].raw.replace(/ \([a-z]{2}\) /g,'');
			console.log("Categoría de wikimapia recuperada: " + JSON.stringify(tag));
			wikimapiaCategoryService.save(tag, function(err, response) {
				if (err)
					console.log("Error al guardar categoría de wikimapia, id: " + tag.id + " title: " + tag.title.replace(/ \([a-z]{2}\) /g,''));
				console.log("Categoría de wikimapia insertada, id: " + tag.id + " title: " + tag.title.replace(/ \([a-z]{2}\) /g,''));
			});
		});
	});
}

function parseHtml(rawHtml) {
	var handler = new htmlparser.DefaultHandler(function (error, dom) {
	    if (error)
	        console.log('Error: ' + error);
	    else
	        console.log('Parsing Done');
	});

	var parser = new htmlparser.Parser(handler);

	parser.parseComplete(rawHtml);

	return handler.dom;
}

fetchCategories();
